package com.frinder.base.server;

import com.frinder.base.ByteBufUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName ClientManagerHandler
 * @Author frinder
 * @Description 管理客户端 handler
 * @Date 2018/11/28 19:37
 * @Version 1.0
 */
@Slf4j
public class ClientManagerHandler extends ChannelInboundHandlerAdapter {

    private ChannelGroup channels;

    public ClientManagerHandler(ChannelGroup channels) {
        super();
        this.channels = channels;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel client = ctx.channel();
        log.info("*** 客户端 {} 连接中……", client.remoteAddress());
        // 将新客户端放入channel group中
        channels.add(client);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel client = ctx.channel();
        log.info("*** 客户端 {} 下线了！", client.remoteAddress());
        // 移除客户端
        channels.remove(client);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel client = ctx.channel();
        log.info("*** 客户端 {} 已连接！", client.remoteAddress());
        // 客户端连接成功后反馈
//        ctx.writeAndFlush(ByteBufUtils.buf("连接成功！", DELIMITER));
//        ctx.writeAndFlush(ByteBufUtils.buf("连接成功！"));
        ctx.writeAndFlush(ByteBufUtils.buf("连接成功！", "\n"));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel client = ctx.channel();
        log.info("*** 客户端 {} 下线中……", client.remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(), cause);
        ctx.close();
    }

}
